package com.zhixin.fans.ks.ui.main.mutual;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhixin.fans.ks.KeyConstant;
import com.zhixin.fans.ks.R;
import com.zhixin.fans.ks.api.CoupleApi;
import com.zhixin.fans.ks.manager.UserInfoManager;
import com.zhixin.fans.ks.ui.base.BaseNeedLoginActivity;
import com.zhixin.fans.ks.ui.utils.GlideImageEngine;

import org.eenie.common.subscribes.ProgressSubscriber;
import org.eenie.common.views.TopBarLayout;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;



public class PostMutualActivity extends BaseNeedLoginActivity implements UploadImgAdapter.OnItemViewClickListener, BaseQuickAdapter.OnItemLongClickListener {
    public static final String ROUTE_PATH = "/mutual/post_mutual";
    @BindView(R.id.top_bar)
    TopBarLayout mTopBar;
    @BindView(R.id.edit_mutual_content)
    EditText mEditMutualContent;
    @BindView(R.id.rv_photo)
    RecyclerView mRvPhoto;

    UploadImgAdapter mUploadImgAdapter;

    CoupleApi mCoupleApi;

    UserInfoManager mUserInfoManager;
    @BindView(R.id.btn_send)
    TextView mBtnSend;


    UploadImg mUploadImg;


    @Override
    public int initContentView() {
        return R.layout.activity_post_mutual;
    }

    @Override
    public void initInjector() {
        mCoupleApi = getApplicationComponent().getApiManager().create(CoupleApi.class);
        mUserInfoManager = getCoupleAppComponent().getUserInfoManager();

    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


        mRvPhoto.setLayoutManager(new GridLayoutManager(mContext, 3));
        mRvPhoto.setAdapter(mUploadImgAdapter = new UploadImgAdapter(1));
        mUploadImgAdapter.setOnItemViewClickListener(this);

        mUploadImgAdapter.setOnItemLongClickListener(this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 3001 && resultCode == RESULT_OK) {
            upload(new File(Matisse.obtainPathResult(data).get(0)));
            mUploadImgAdapter.notifyDataSetChanged();
        }
    }


    private void chooseImg() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(1)
                .capture(true)
                .captureStrategy(new CaptureStrategy(false, "org.eenie.couple.fileprovider"))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideImageEngine())
                .forResult(3001);
    }

    @Override
    public void onEmptyClick() {
        chooseImg();
    }

    @Override
    public void onItemClick(UploadImg uploadImg) {

    }


    public void upload(File file) {


        mCoupleApi.uploadFile(file)
                .subscribe(new ProgressSubscriber<JSONObject>() {
                    @Override
                    public void onNext(JSONObject jsonObject) {
                        try {
                            mUploadImg = new UploadImg(jsonObject.getString("data"));
                            mUploadImgAdapter.setNewData(Arrays.asList(mUploadImg));
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ToastUtils.showShort("图片上传失败");
                        }


                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }


    private void sendMutual() {
        mCoupleApi.sendMutuals(mUserInfoManager.getValue().getU_id(), mUploadImg != null ? mUploadImg.getPath() : "", mEditMutualContent.getText().toString())
                .subscribe(new ProgressSubscriber<String>(mContext, "发布中...") {
                    @Override
                    public void onNext(String msg) {
                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(new Intent(KeyConstant.ACTION_UPDATE_MUTUAL));
                        finish();
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }


    @OnClick(R.id.btn_send)
    public void onViewClicked() {
        if (!TextUtils.isEmpty(mEditMutualContent.getText())) {
            sendMutual();
        } else {
            ToastUtils.showShort("请填写互动的内容");
        }
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {

        UploadImg uploadImg = (UploadImg) adapter.getItem(position);

        if (uploadImg.getType() != 1) {
            mUploadImgAdapter.setNewData(Arrays.asList(new UploadImg(1)));
            mUploadImg = null;
        }

        mUploadImgAdapter.notifyDataSetChanged();
        return true;
    }

}
